#! /usr/bin/env python
# -*- coding: utf8 -*-

# Alexandre Coster <acoster@rhrk.uni-kl.de>
# AG DBIS - Technische Universität Kaiserslautern

import os
import sys

if sys.version_info[:2] == (2, 5):
    from xml.etree import cElementTree as et
else:
    import cElementTree as et

import load
import prob
import trans

class config(object):
    def __init__(self, fname):
        self.__algorithms      = {}
        self.__probDistr       = {}
        self.__tags            = []
        self.__transformations = {}

        self.__addIDs          = None
        self.__root            = None

        self.__confRoot = et.parse(fname).getroot()

        for i in self.__confRoot.findall("./distributions/distribution"):
            name                   = i.find("name").text.strip()
            self.__probDistr[name] = prob.probDistr(i)

        algorithms = self.__load_algorithms()
        for i in self.__confRoot.findall("./algorithms/algorithm"):
            name = i.find("name").text.strip()
            if i.find("base") == None:
                base = i.find("baseAlgorithm").text.strip().lower()
            else:
                base = i.find("base").text.strip().lower()
            self.__algorithms[name] = algorithms[base](i)

        for i in self.__confRoot.findall("./transformations/transformation"):
            name                         = i.find("name").text.strip()
            self.__transformations[name] = trans.transform(i, self.__probDistr, self.__algorithms, self.__transformations)

            if self.__transformations[name].isRoot:
                self.__root = name

        if not self.__root:
            print "(config error) A root should be set."
            sys.exit(1)

        optionsRoot = self.__confRoot.find("options")

        self.__addIDs  = False
        self.__shuffle = False

        if optionsRoot != None:
            self.__addIDs  = (optionsRoot.find("addIDs")  != None)
            self.__shuffle = (optionsRoot.find("shuffle") != None)
        self.__tags    =  self.__transformations.keys()

    def __load_algorithms(self):
        path =  "/".join(os.path.abspath(sys.modules[__name__].__file__).split("/")[:-1]) + "/algo"
        return dict([(x.name.lower(), x) for x in load.loadPlugins(path)])

    @property
    def addIDs(self):
        return self.__addIDs

    @property
    def algorithms(self):
        return self.__algorithms

    @property
    def probDistr(self):
        return self.__probDistr

    @property
    def root(self):
        return self.__root

    @property
    def shuffle(self):
        return self.__shuffle

    @property
    def tags(self):
        return self.__tags

    @property
    def transformations(self):
        return self.__transformations
